package com.gjy.mybatis.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-10-24 10:51:22
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class ExecutorInterceptor implements Interceptor {

    private static final Logger log = LoggerFactory.getLogger(ExecutorInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        Object obj = invocation.getArgs()[1];
        Object proceed = invocation.proceed();

        SqlCommandType sqlCommandType = statement.getSqlCommandType();

        try {
            Field field = obj.getClass().getDeclaredField("region");
            field.setAccessible(true);

            if (SqlCommandType.INSERT.equals(sqlCommandType)) { // 新增操作
                field.set(obj, "insert_" + field.get(obj));
            } else if (SqlCommandType.UPDATE.equals(sqlCommandType)) { // 修改操作
                field.set(obj, "update_" + field.get(obj));
            }
        } catch (Exception e) {
            log.error("e: {}", e.getMessage());
            return proceed;
        }

        BoundSql sql = statement.getSqlSource().getBoundSql(obj);
        log.info("sql = {}", sql.getSql());

        return proceed;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
